﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Castle.ActiveRecord;

namespace SinsenWeb.Helpers
{

    public class ARTypeConverter<T> : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value.GetType() == typeof(string))
            {
                return ActiveRecordMediator.FindByPrimaryKey(typeof(T), int.Parse(value.ToString()));
            }
            return base.ConvertFrom(context, culture, value);
        }
    }

    public class ARGetter<T>
    {
        public static T Get(int id)
        {
            return (T)ActiveRecordMediator.FindByPrimaryKey(typeof(T), id);
        }

        public static T Get(string idString)
        {
            if(idString==null)
            {
                return default(T);
            }
            return (T)ActiveRecordMediator.FindByPrimaryKey(typeof(T), int.Parse(idString));
        }

    }



}
